home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2932 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Wed, 24 Jan 96 20:50:54 GMT
  6. Organization: none
  7. Distribution: world
  8. Message-ID: <822516654snz@genesis.demon.co.uk>
  9. References: <AAQgE1nWVS@csg.spb.su>
  10. Reply-To: fred@genesis.demon.co.uk
  11. X-NNTP-Posting-Host: genesis.demon.co.uk
  12. X-Newsreader: Demon Internet Simple News v1.27
  13. X-Mail2News-Path: genesis.demon.co.uk
  14.  
  15. In article <AAQgE1nWVS@csg.spb.su>
  16.            alex@csg.spb.su "Alexander N. Pryguichev" writes:
  17.  
  18. >There is well known solution:
  19. >
  20. >Boolean IsPowerOfTwo(unsigned long x)
  21. >{ long y;
  22. >  y = x & 0x55555555; y += (x >> 1) & 0x55555555;
  23. >  x = y & 0x33333333; x += (y >> 2) & 0x33333333;
  24. >  y = x & 0x0F0F0F0F; y += (x >> 4) & 0x0F0F0F0F;
  25. >  x = y & 0x00FF00FF; x += (y >> 8) & 0x00FF00FF;
  26. >  y = x & 0x0000FFFF; y += (x >>16) & 0x0000FFFF;
  27.  
  28. That is a well known method for counting the number of 1 bits in a 32 bit
  29. value. However it isn't used for determining whether a value is a power of 2
  30. since, as has been posted, a much better approach exists.
  31.  
  32. >  return y == 1;
  33. >}
  34.  
  35. -- 
  36. -----------------------------------------
  37. Lawrence Kirby | fred@genesis.demon.co.uk
  38. Wilts, England | 70734.126@compuserve.com
  39. -----------------------------------------
  40.